package com.yundasys.lab13mybatisplus.algorithm;

import com.google.common.collect.Lists;
import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

/**
 * @PACKAGE_NAME: com.yundasys.lab13mybatisplus.algorithm
 * @NAME: OrderShardingAlgorithm
 * @USER: jiangta
 * @DATE: 2022/2/21
 * @TIME: 4:19 下午
 * @PROJECT_NAME: springboot-labs
 */
public class OrderComplexShardingAlgorithm implements ComplexKeysShardingAlgorithm<Integer> {


    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, ComplexKeysShardingValue<Integer> shardingValue) {
        Map<String, Collection<Integer>> columnNameAndShardingValuesMap = shardingValue.getColumnNameAndShardingValuesMap();
        Integer order_id = columnNameAndShardingValuesMap.get("order_id").iterator().next();
        Integer user_id = columnNameAndShardingValuesMap.get("user_id").iterator().next();
        Iterator<String> realTableNameIte = availableTargetNames.iterator();
        while(realTableNameIte.hasNext()) {
            String next = realTableNameIte.next();
            if(next.endsWith(String.valueOf(order_id%2))) {
                return Lists.newArrayList(next);
            }
        }
        return null;
    }
}
